package de.tum.getraenke;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 *
 * @author gokhan
 */
public class OrderStatusActivity extends Activity implements Button.OnClickListener {

	private static final String TAG = OrderStatusActivity.class.getSimpleName();
	
    private Drink orderedDrink;
    private int OrderAmount;
    private Button OrderButton;
    private Button CancelButton;
    private Button FavoritesButton;
    private TextView OrderedItemLabel;
    private EditText OrderAmountEditText;
    private TextView OrderedPackingLabel;
    private TextView OrderedSizeLabel;
    private TextView OrderedPriceLabel;
    private ImageView OrderedImageView;
    public static final int REQUEST_CODE = 0x0ba7c0df;
    private DrinkDBHandler dbHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.status);

        orderedDrink = new Drink();
        orderedDrink.setGtin(this.getIntent().getStringExtra("gtin"));
        orderedDrink.setName(this.getIntent().getStringExtra("name"));
        orderedDrink.setPacking(this.getIntent().getStringExtra("packing"));
        orderedDrink.setSize(this.getIntent().getDoubleExtra("size", 0.0));
        orderedDrink.setPrice(this.getIntent().getDoubleExtra("price", 0.0));
        orderedDrink.setDeposit(this.getIntent().getDoubleExtra("deposit", 0.0));
        orderedDrink.setImage(this.getIntent().getStringExtra("image"));
        
        OrderAmountEditText = (EditText) findViewById(R.id.OrderAmountEditText);
        OrderButton = (Button) findViewById(R.id.OrderButton);
        CancelButton = (Button) findViewById(R.id.CancelButton);
        FavoritesButton = (Button) findViewById(R.id.FavoritesButton);

        // set name
        OrderedItemLabel = (TextView) findViewById(R.id.OrderedItemLabel);
        OrderedItemLabel.setText(orderedDrink.getName());

        // set packing
        OrderedPackingLabel = (TextView) findViewById(R.id.OrderedPackingLabel);
        OrderedPackingLabel.setText(orderedDrink.getPacking());

        // set size
        OrderedSizeLabel = (TextView) findViewById(R.id.OrderedSizeLabel);
        if (orderedDrink.getSize() > 0.0) {
            OrderedSizeLabel.setText(String.valueOf(orderedDrink.getSize()) + "l");
        }

        // set price
        OrderedPriceLabel = (TextView) findViewById(R.id.OrderedPriceLabel);
        OrderedPriceLabel.setText(String.valueOf(
                (double) Math.round((orderedDrink.getPrice() + orderedDrink.getDeposit()) * 100) / 100)
                + "€ (Deposit " + String.valueOf(orderedDrink.getDeposit()) + "€)");

        // set picture
        OrderedImageView = (ImageView) findViewById(R.id.OrderedImageView);
        downloadFile(orderedDrink.getImage());

        // amount
        OrderAmount = 0;
        OrderButton.setOnClickListener(this);
        CancelButton.setOnClickListener(this);
        FavoritesButton.setOnClickListener(this);
        
        // get database
        dbHandler = new DrinkDBHandler(this);
        
        // store to database, if necessary
        if(dbHandler.getDrinkIdByGtin(orderedDrink.getGtin()) == -1) {
        	dbHandler.insertDrink(orderedDrink);
        } else {
        	dbHandler.updateDrinkIfNecessary(orderedDrink);
        }
    }

    public Drink getOrderedDrink() {
        return orderedDrink;
    }

    public void setOrderAmount(int OrderNumber) {
        this.OrderAmount = OrderNumber;
    }

    public int getOrderAmount() {
        return OrderAmount;
    }

    public void onClick(View arg0) {

        if (arg0.getId() == R.id.OrderButton) {
            //IF ORDER IS CLICKED
            try {
                OrderAmount = Integer.valueOf(OrderAmountEditText.getText().toString());
            } catch (Exception e) {
                Toast.makeText(this, "Please choose valid amount between 1 and 10", Toast.LENGTH_LONG).show();
            }
            if (OrderAmount <= 0 || OrderAmount > 10) {
                Toast.makeText(this, "Please choose valid amount between 1 and 10", Toast.LENGTH_LONG).show();
            } else {
            	// store to our order database
            	dbHandler.insertOrder(orderedDrink, OrderAmount);
            	// get back to main activity
                Intent in = this.getIntent();
                //PUT THE ORDER AMOUNT TO INTENT TO RETURN IT
                in.putExtra("amount", OrderAmount);
                this.setResult(RESULT_OK, in);
                finish();
            }
        } else if (arg0.getId() == R.id.FavoritesButton) {
            // add to favorites
        	if(dbHandler.setFavorite(orderedDrink, true) == 1) {
        		Toast.makeText(this,
                        "Drink added to favorites list",
                        Toast.LENGTH_LONG).show();
        	} else {
        		Toast.makeText(this,
                        "Drink is already in favorites list",
                        Toast.LENGTH_LONG).show();
        	}
        } else if (arg0.getId() == R.id.CancelButton) {
            //IF CANCEL BUTTON ISCLICKED
            Intent in = this.getIntent();
            this.setResult(RESULT_CANCELED, in);
            finish();
        }
    }

    public static OrderResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                String gtin = intent.getExtras().getString("gtin");
                int amount = intent.getExtras().getInt("amount");
                return new OrderResult(gtin, amount);
            }
        }
        return null;
    }

    void downloadFile(String fileUrl) {
        URL myFileUrl = null;
        try {
            myFileUrl = new URL(fileUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return;
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            //5 seconds timeout
            conn.setConnectTimeout(5000);
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();

            Bitmap bmImg = BitmapFactory.decodeStream(is);
            OrderedImageView.setImageBitmap(bmImg);
            conn.disconnect();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }


    }
}
